package servlets.payPalServlets;

import java.io.IOException;
import java.net.URL;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import managers.JsonManager;

import org.jsoup.Jsoup;

import structures.User;

public class PayPalReturnServlet extends HttpServlet {

	private static final long serialVersionUID = -3883001595007011611L;
	private static final String GETUSERURLBASE = "http://localhost:8080/ISellToYouRESTWebService/LoginByID?";
	
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response){
		
		String idUser,answer, success;
		URL url;
		JsonManager jsonManager;
		User user = null;
		jsonManager = new JsonManager();
		idUser = request.getParameter("idUser");
		success = request.getParameter("success");
		
		try {
			// Lettura da DB dell'utente che acquista
			url = new URL(GETUSERURLBASE + "idUser=" + idUser);
			answer = Jsoup.connect(url.toString()).ignoreContentType(true).execute().body();
			
			if(answer.equals("null"))
				throw new Exception();
			
			user = jsonManager.toUser(answer);
			request.getSession().setAttribute("user", user);
			
			response.sendRedirect(request.getContextPath() + "/confirmBuy.jsp?success=" + success);

		} catch (Exception e1) {
			e1.printStackTrace();
			try {
				response.sendRedirect(request.getContextPath() + "/confirmBuy.jsp?success=false");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
